import 'dart:io';
import 'dart:typed_data';

import 'package:path_provider/path_provider.dart';
import 'package:image/image.dart' as img;
import 'package:video_thumbnail/video_thumbnail.dart';

class ImgUtils {
  /// 根据路径截取文件名
  /// withOutSuffix: 不带后缀
  static String getFileName(String path, {bool withOutSuffix = false}) {
    List<String>? strs = path.split("/");
    print('文件名 --- ${strs.last}');

    if (withOutSuffix) {
      // 不带后缀
      strs = strs.last.split(".");
      return strs.first;
    }
    return strs.last;
  }

  // 获取文件后缀名
  static String getFileExtension(String filePath) {
    // 找到最后一个点（.）的位置
    int lastDotIndex = filePath.lastIndexOf('.');
    if (lastDotIndex == -1) return ''; // 无后缀
    return filePath.substring(lastDotIndex); // 包含点
  }

  /// 获取视频缩略图
  static Future<String> getThumbnail(String url) async {
    String? thumbnailPath;
    // 根据缩略图路径规则生成路径
    thumbnailPath =
        '${(await getTemporaryDirectory()).path}/${getFileName(url, withOutSuffix: true)}.png';

    // 判断缩略图是否存在，不存在则重新生成缩略图
    File thumbnail = File(thumbnailPath);
    if (!thumbnail.existsSync()) {
      thumbnailPath = await VideoThumbnail.thumbnailFile(
        video: url,
        thumbnailPath: (await getTemporaryDirectory()).path,
        imageFormat: ImageFormat.PNG,
        maxHeight: 200,
        quality: 100,
      );
      thumbnail = File(thumbnailPath ?? '');
    }

    return thumbnail.path;
  }

  // 图片格式转换
  static Future<File> convertImageFormat(File originalFile,
      {String format = 'png', int quality = 90}) async {
    // 读取原始图片数据
    final bytes = await originalFile.readAsBytes();

    // 使用image库解码
    final image = img.decodeImage(bytes);
    if (image == null) throw Exception('无法解码图片');

    // 转换为指定格式
    final Uint8List convertedBytes;
    if (format.toLowerCase() == 'png') {
      convertedBytes = Uint8List.fromList(img.encodePng(image));
    } else {
      convertedBytes =
          Uint8List.fromList(img.encodeJpg(image, quality: quality));
    }

    // 保存到临时文件
    final tempDir = await getTemporaryDirectory();
    final fileName =
        'avatar_${DateTime.now().millisecondsSinceEpoch}.${format.toLowerCase()}';
    final file = File('${tempDir.path}/$fileName');
    await file.writeAsBytes(convertedBytes);

    return file;
  }
}
